<template>
  <div>
    <el-dialog :center="true" :title="title" :visible.sync="formVisibleDown" width="60%" :before-close="() => {$emit('update:formVisibleDown', false), $refs['ruleForm'].resetFields()}" @open="openDialog">
      <div v-loading="loading" class="from_box">
        <el-form ref="ruleForm" :model="ruleForm" inline :rules="rules" label-width="140px" class="dialog-form-expand2">
          <el-form-item label="售后类型" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择售后类型" clearable @change="changeType">
              <el-option v-for="(item, index) in optionType" :key="index" :disabled="item.disabled" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.type==='1'" label="退款类型" prop="refund_type">
            <el-select v-model="ruleForm.refund_type" placeholder="请选择退款类型" clearable @change="changeReundTypeHandler">
              <el-option v-for="(item, index) in optionTypeReturn" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="售后原因" prop="sale_reason">
            <el-select v-model="ruleForm.sale_reason" placeholder="请选择售后原因" clearable>
              <el-option v-for="(item, index) in optionReason" :key="index" :value="item.value" :label="item.label" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.type==='3'" label="补货类型" prop="replenish_type">
            <el-select v-model="ruleForm.replenish_type" placeholder="请选择补货类型" clearable>
              <el-option v-for="(item, index) in optionTypeReplenish" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.type==='4'|| ruleForm.type==='3'" :label="`${ruleForm.type==='2'?'退货':(ruleForm.type==='3' ? '补货': '召回')}物流`" prop="refund_logistics">
            <el-select v-model="ruleForm.refund_logistics" :disabled="ruleForm.type==='4'?true:false" :placeholder="`请选择${ruleForm.type==='2'?'退货':(ruleForm.type==='3' ? '补货': '召回')}物流`" clearable>
              <el-option v-for="item in logisticsCompanyList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.type==='4'" label="物流单号" prop="logistics_no">
            <el-input v-model="ruleForm.logistics_no" :disabled="ruleForm.type==='4'?true:false" placeholder="请输入物流单号" />
          </el-form-item>
          <el-form-item v-if="ruleForm.type==='4' || ruleForm.type==='2'" :label="`${ruleForm.type==='2'?'退货':'召回'}实体库`" prop="storage_id">
            <el-select v-model="ruleForm.storage_id" placeholder="请选择退货实体库" clearable @change="changeStorage">
              <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.storage_id" :label="`仓库地址`" prop="storage_id">
            <span>{{ ruleForm.storage_address }}</span>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="ruleForm.remarks" placeholder="请填写备注" type="textarea" autosize />
          </el-form-item>
        </el-form>
        <div v-if="ruleForm.type !== '5'" class="header_title_box">
          <h2 style="margin-right:50px">
            {{ ruleForm.replenish_type === 2 ?'配件信息': '商品信息' }}
          </h2>
          <div v-if="ruleForm.replenish_type === 2">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addField">新增</el-button>
          </div>
        </div>
        <!-- 配件信息 -->
        <div v-if="ruleForm.replenish_type === 2">
          <el-form ref="formData" :rules="model.rules" :model="model" class="dialog-form-expand3">
            <el-table :data="model.fields" tooltip-effect="dark" style="width: 100%" border>
              <el-table-column align="center" label="操作" width="150">
                <template slot-scope="field">
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteFieldPrat(field.row)" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="配件编码">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.goods_id'" :rules="model.rules.goods_id">
                    <el-select v-model="field.row.goods_id" size="mini" filterable clearable placeholder="请输入关键词" @change="changePart">
                      <el-option v-for="item in partList" :key="item.value" :disabled="item.disabled" :label="`${item.code}(${item.name_ch})`" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="配件名称">
                <template slot-scope="field">
                  <el-form-item>
                    <span>{{ field.row.name }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="配件数量">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.quantity_purchased'" :rules="model.rules.quantity_purchased">
                    <el-input v-model="field.row.quantity_purchased" placeholder="请输入数量" />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <!-- 商品信息 -->
        <div v-if="ruleForm.type === '1' ||ruleForm.type === '2' ||ruleForm.type === '4' || ruleForm.replenish_type === 1" v-loading="loadingTable">
          <el-form ref="formData" :rules="model.rules" :model="model" class="dialog-form-expand3">
            <el-table ref="multipleTable" :data="model.fieldsProduct" tooltip-effect="dark" style="width: 100%" border @selection-change="selectionChange">
              <el-table-column v-if="ruleForm.type !== '1'" key="1" type="selection" width="55" :selectable="checkSelectable" />
              <!-- <el-table-column align="center" label="缩略图" prop="url" /> -->
              <el-table-column key="2" align="center" label="缩略图">
                <template slot-scope="scope">
                  <el-image style="width: 50px; height: 50px" fit="contain" :src="scope.row.goods_pic">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline" />
                    </div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column key="3" align="center" label="系统sku" prop="goods_codes">
                <template slot-scope="scope">
                  {{ scope.row.goods_codes?scope.row.goods_codes:scope.row.goods_code }}
                </template>
              </el-table-column>
              <el-table-column key="4" align="center" label="多箱分组名称" prop="goods_group_name" />
              <el-table-column key="5" align="center" prop="status_text" label="状态">
                <template slot-scope="scope">
                  {{ deliveryState(scope.row) }}
                </template>
              </el-table-column>
              <el-table-column key="6" align="center" label="商品名称" :prop="`${ruleForm.type=='1'?'name':'goods_name'}`" show-overflow-tooltip />
              <el-table-column key="7" align="center" label="单价" prop="transaction_price_value" />
              <el-table-column key="8" align="center" label="币别" prop="transaction_price_currencyid" />
              <el-table-column key="9" align="center" label="数量" prop="quantity_purchased" />
              <!-- batch_no -->
              <el-table-column key="10" align="center" label="金额(不含税)" prop="transaction_price_value_all" />
              <el-table-column key="11" align="center" label="税费" prop="tax_amount_value">
                <template slot-scope="scope">
                  <app-price :price="scope.row.tax_amount_value" />
                </template>
              </el-table-column>
              <el-table-column v-if="ruleForm.type==='2' || ruleForm.type==='4'" key="12" align="center" label="批次" prop="batch_no" />
              <el-table-column v-if="ruleForm.type==='4'" key="13" align="center" label="召回数量" prop="quantity_purchased" />
              <el-table-column v-if="ruleForm.type==='2'" key="14" align="center" label="已退金额" prop="after_amount" />
              <el-table-column v-if="ruleForm.type==='2'" key="15" align="center" label="已退数量" prop="return_num" />
              <el-table-column v-if="ruleForm.type==='2'" key="16" align="center" label="退货数量" width="130">
                <template slot-scope="field">
                  <el-form-item :prop="'fieldsProduct.' + field.$index + '.recall_num'" :rules="model.rules.recall_num">
                    <el-input-number v-model="field.row.recall_num" size="mini" controls-position="right" :min="1" :precision="0" :max="(field.row.quantity_purchased-field.row.return_num)" style="width:100px" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="ruleForm.type==='3'" key="17" align="center" :label="`补货数量`" width="130">
                <template slot-scope="field">
                  <el-form-item :prop="'fieldsProduct.' + field.$index + '.quantity_purchased'" :rules="model.rules.recall_num">
                    <el-input-number v-model="field.row.quantity_purchased" size="mini" controls-position="right" :min="1" :precision="0" style="width:100px" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="ruleForm.type==='2' || ruleForm.type==='1'" key="18" width="150" align="center" label="退款金额">
                <template slot-scope="field">
                  <el-form-item :prop="'fieldsProduct.' + field.$index + '.fill_amount'" :rules="model.rules.fill_amount">
                    <el-input v-model="field.row.fill_amount" size="mini" placeholder="退款金额" autocomplete="off" clearable />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <!-- 地址信息 -->
        <div v-if="ruleForm.type === '5'||ruleForm.type === '3'">
          <div class="header_title_box">
            <h2>收货人信息 <span class="el-icon-edit-outline pointer blue" @click="disableAddress=!disableAddress" /></h2>
          </div>
          <el-form ref="formFields" :model="formFieldsData" :rules="formFieldsRules" label-width="140px" inline class="dialog-form-expand">
            <!-- 买家的名字 -->
            <el-form-item label="买家名字" :label-width="formLabelWidth" prop="address_name">
              <el-input v-model.trim="formFieldsData.address_name" :disabled="disableAddress" placeholder="请输入买家名字" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的姓氏 buyer_lastname
            <el-form-item label="买家姓氏" :label-width="formLabelWidth" prop="buyer_lastname">
              <el-input v-model.trim="formFieldsData.buyer_lastname" :disabled="disableAddress" placeholder="请输入买家姓氏" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item> -->
            <!-- 买家的邮箱 -->
            <el-form-item label="买家邮箱" :label-width="formLabelWidth" prop="address_email">
              <el-input v-model.trim="formFieldsData.address_email" :disabled="disableAddress" placeholder="请输入买家邮箱" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家电话 -->
            <el-form-item label="买家电话" :label-width="formLabelWidth" prop="address_phone">
              <el-input v-model.trim="formFieldsData.address_phone" :disabled="disableAddress" placeholder="请输入买家电话" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的国家的代码 -->
            <el-form-item label="国家" :label-width="formLabelWidth" prop="address_country">
              <el-select v-model="formFieldsData.address_country" :disabled="disableAddress" placeholder="请选择店铺" filterable clearable style="width:177px">
                <el-option v-for="item in optionpCountry" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <!-- 买家的州/省（英文简写缩写） -->
            <el-form-item label="州/省" :label-width="formLabelWidth" prop="address_stateorprovince">
              <el-select v-model="formFieldsData.address_stateorprovince" :disabled="disableAddress" placeholder="请选择州/省" filterable clearable style="width:177px" @change="changeState">
                <el-option v-for="item in optionStates" :key="`${item.id}States`" :label="`${item.code}(${item.cname})`" :value="item.code" />
              </el-select>
            </el-form-item>
            <!-- 买家的城市 (英文全称) address_cityname-->
            <el-form-item label="城市" :label-width="formLabelWidth" prop="address_cityname">
              <el-select v-model="formFieldsData.address_cityname" :disabled="disableAddress" placeholder="请选择城市" filterable clearable style="width:177px" @change="changeCity">
                <el-option v-for="item in optionCity" :key="`${item.id}city`" :label="`${item.name}(${item.cname})(${item.code})`" :value="item.lower_name" />
              </el-select>
            </el-form-item>
            <!-- 买家的邮编 -->
            <el-form-item label="邮编" :label-width="formLabelWidth" prop="address_postalcode">
              <el-select v-model="formFieldsData.address_postalcode" :disabled="disableAddress" placeholder="请选择邮编" filterable clearable style="width:177px" @change="inputChange">
                <el-option v-for="item in optionPostalCode" :key="item.zip" :label="item.zip" :value="item.zip" />
              </el-select>
            </el-form-item>
            <!-- 买家的街道1 -->
            <el-form-item label="街道1" :label-width="formLabelWidth" prop="address_street1">
              <el-input v-model.trim="formFieldsData.address_street1" :disabled="disableAddress" placeholder="请输入街道1" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的街道2 -->
            <el-form-item label="街道2" :label-width="formLabelWidth" prop="address_street2">
              <el-input v-model.trim="formFieldsData.address_street2" :disabled="disableAddress" placeholder="请输入街道2" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的街道3 -->
            <el-form-item label="街道3" :label-width="formLabelWidth" prop="address_street3">
              <el-input v-model.trim="formFieldsData.address_street3" :disabled="disableAddress" placeholder="请输入街道3" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
          </el-form>
        </div>
        <div>
          <div style="text-align: center; margin-top:50px">
            <el-button type="primary" :loading="isbtn" @click="submitForm('ruleForm')">保存</el-button>
            <el-button @click="handleCancelDown">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  warehouseShop,
  statesList,
  cityList,
  cityPostalCode, partListProduct, lforwarderData
} from '@/utils/publicData'
// import formOperate from '@/layout/mixin/formOperate'
import { accMul, objContrast } from '@/utils/index'
// import { defaults } from 'js-cookie'
export default {
  //   mixins: [formOperate],
  props: {
    formVisibleDown: {
      type: Boolean,
      default: false
    },
    optionsModul: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    status: {
      type: String,
      default: ''
    },
    shopId: {
      type: String,
      default: ''
    },
    isRefund: { // 是否可退款
      type: Boolean,
      default: true
    }
  },
  data() {
    var validatename = (rule, value, callback) => {
      if (!this.formFieldsData.address_name.match(/^[\u4e00-\u9fa5a-zA-Z0-9 ]+$/)) {
        callback(new Error('字符且不能存在特殊字符'))
      } else {
        callback()
      }
    }
    return {
      partList: [],
      optionpCountry: [{
        value: 'US',
        label: 'United States'
      }],
      selectionData: [],
      optionStates: [],
      optionCity: [],
      optionPostalCode: [],
      disableAddress: false,
      formLabelWidth: '140px',
      formFieldsDataOld: {},
      formFieldsData: {
        buyer_firstname: '',
        buyer_lastname: '',
        address_email: '',
        address_phone: '',
        address_postalcode: '',
        address_country: '',
        address_country_name: '',
        address_stateorprovince: '',
        address_cityname: '',
        address_street1: '',
        address_street2: '',
        address_street3: ''
      },
      warehouseList: [],
      loadingTable: false,
      // 1-客户无理由退款退货 2-描述不符 3-包装问题 4-质量问题 5-物流问题
      optionReason: [
        {
          label: '客户无理由退款退货',
          value: '1'
        },
        {
          label: '描述不符',
          value: '2'
        },
        {
          label: '包装问题',
          value: '3'
        },
        {
          label: '质量问题',
          value: '4'
        },
        {
          label: '物流问题',
          value: '5'
        },
        {
          label: '其他',
          value: '6'
        }
      ],
      // 退款类型 1-部分退款 2-全部退款
      optionTypeReturn: [
        {
          label: '部分退款',
          value: '1'
        },
        {
          label: '全部退款',
          value: '2'
        }
      ],
      // 1-仅退款 2-退货退款 3-补货 4-召回 5-修改地址
      optionType: [
        {
          label: '仅退款',
          value: '1',
          disabled: false
        },
        {
          label: '退货退款',
          value: '2',
          disabled: false
        },
        {
          label: '补货',
          value: '3',
          disabled: false
        },
        {
          label: '召回',
          value: '4',
          disabled: false
        },
        {
          label: '修改地址',
          value: '5',
          disabled: false
        }
      ],
      // 补货类型
      optionTypeReplenish: [
        {
          label: '整件补货',
          value: 1
        },
        {
          label: '配件补货',
          value: 2
        }
      ],
      ruleForm: {
        type: '', // 类型
        sale_reason: '', // 售后原因
        remarks: '', // 备注
        refund_type: '', // 退款类型
        fill_amount: '', // 退款金额
        refund_amount: '', // 退款金额
        recall_num: 0, // 退款数量
        refund_logistics: '', // 退货物流
        storage_id: '', // 仓储id
        storage_address: '', // 仓储地址
        replenish_type: '', // 补货类型 1-整件补货 2-配件补货
        logistics_no: ''
      },
      isbtn: false,
      rules: {
        logistics_no: [
          { required: true, message: '请输入物流单号', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择售后类型', trigger: 'blur' }
        ],
        sale_reason: [
          { required: true, message: '请选择售后原因', trigger: 'blur' }
        ],
        refund_type: [
          { required: true, message: '请选择退款类型', trigger: 'blur' }
        ],
        refund_logistics: [
          { required: true, message: '请选择物流类型', trigger: 'blur' }
        ],
        storage_id: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        replenish_type: [{ required: true, message: '请选择补货类型', trigger: 'blur' }]

      },
      formFieldsRules: {
        address_name: [{
          required: true,
          message: '请输入姓名',
          trigger: 'change'
        },
        {
          validator: validatename,
          trigger: 'change'
        },
        // {
        //   required: true,
        //   pattern: /^[\u4e00-\u9fa5a-zA-Z0-9 ]+$/,
        //   message: '字符且不能存在特殊字符',
        //   trigger: 'change'
        // },
        {
          required: true,
          min: 1,
          max: 30,
          message: '长度在 1 到 20 个字符且不能存在特殊字符',
          trigger: 'blur'
        }],
        // buyer_firstname: [{
        //   required: true,
        //   message: '请输入名',
        //   trigger: 'blur'
        // }, {
        //   min: 1,
        //   max: 30,
        //   message: '长度在 1 到 20 个字符',
        //   trigger: ['blur', 'change']
        // }],
        // buyer_lastname: [{
        //   required: true,
        //   message: '请输入姓',
        //   trigger: 'blur'
        // }, {
        //   min: 1,
        //   max: 30,
        //   message: '长度在 1 到 20 个字符',
        //   trigger: ['blur', 'change']
        // }],
        address_email: [{
          required: false,
          message: '请输入邮箱地址',
          trigger: 'blur'
        }, {
          type: 'email',
          message: '请输入正确的邮箱地址',
          trigger: ['blur', 'change']
        }],
        address_phone: [{
          required: true,
          message: '请输入电话',
          trigger: 'blur'
        }],
        address_country: [{
          required: true,
          message: '请选择国家',
          trigger: 'blur'
        }],
        address_stateorprovince: [{
          required: true,
          message: '请选择州/省',
          trigger: 'blur'
        }],
        address_cityname: [{
          required: true,
          message: '请选择州/省',
          trigger: 'blur'
        }],
        address_postalcode: [{
          required: true,
          message: '请选择州/省',
          trigger: 'blur'
        }]
      },
      model: {
        rules: {
          recall_num: { required: true, message: '必填字段', trigger: 'blur' },
          fill_amount: [{ required: true, message: '必填字段', trigger: 'blur' },
            { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多四二位小数', trigger: 'change' }],
          goods_id: { required: true, message: '必填字段', trigger: 'blur' },
          quantity_purchased: { required: true, message: '必填字段', trigger: 'blur' }
        },
        fieldsProduct: [],
        fields: [this.getColumn()]
      },
      productAfter: [],
      products: [],
      logisticsCompanyList: [], // 物流公司
      loading: false
    }
  },
  created() {
    statesList().then((data) => {
      this.optionStates = data
      if (this.id) {
        this.disabled = true
        this.disableAddress = true
        this.disableProduct = true
      }
    })
    this.getLogisticsCompany()
  },
  methods: {
    // 状态
    deliveryState(row) {
      let str = ''
      switch (row.delivery_state) {
        case 1:
          str = '待发货'
          break
        case 2:
          str = '已发货'
          break
        case 3:
          str = '运输中'
          break
        case 4:
          str = '配送中'
          break
        case 5:
          str = '已收货'
          break
        case 6:
          str = '作废'
          break
        default:
          str = ''
      }
      return str
    },
    // 获取物流公司 数据字典
    getLogisticsCompany() {
      lforwarderData().then(res => {
        this.logisticsCompanyList = res
      })
    },
    // 修改退款类型handler
    changeReundTypeHandler(e) {
      const vm = this
      // 全部退款
      if (e === '2') {
        vm.model.fieldsProduct.forEach(e => {
          e.fill_amount = e.transaction_price_value_all
        })
      }
    },
    // 修改
    changePart(val) {
      const vm = this
      const list = vm.partList.filter((item) => {
        return item.id === val
      }).map((arr) => {
        return {
          goods_id: arr.id,
          goods_code: arr.code,
          goods_type: '1',
          quantity_purchased: '1',
          name: arr.name_ch,
          image_url: arr.image_url
        }
      })
      // 删除当前
      vm.model.fields = vm.model.fields.filter(function(value, key) {
        return val !== value.goods_id
      })
      vm.model.fields.push(list[0])
      vm.partList = vm.partList.map((arr) => {
        if (arr.id === val) {
          arr.disabled = true
        }
        return arr
      })
    },
    // 删除
    deleteFieldPrat(tag) {
      const vm = this
      vm.model.fields.splice(vm.model.fields.indexOf(tag), 1)
      vm.partList = vm.partList.map((arr) => {
        if (arr.id === tag.goods_id) {
          arr.disabled = false
        }
        return arr
      })
    },
    // 新增选项
    addField() {
      this.model.fields.push(this.getColumn())
    },
    // 数据列表
    getColumn() {
      return {
        'goods_id': '',
        'goods_code': '',
        'goods_group_name': '',
        'quantity_purchased': '1',
        'goods_type': 1,
        'name': '',
        'id': ''
      }
    },
    // 修改省份
    changeState(value) {
      // console.log('========changeStatevalue====', value, this.optionStates)
      const address_stateorprovince = this.optionStates.filter((arr) => {
        return arr.code === value
      })
      // console.log('address_stateorprovince', address_stateorprovince)
      cityList(address_stateorprovince[0].id).then(data => {
        this.optionCity = data
      })
      // console.log('======000000000000==changeState====')
      this.formFieldsData.address_postalcode = ''
      this.formFieldsData.address_cityname = ''
    },
    // 城市
    changeCity(value) {
      const obj = this.optionCity.filter((arr) => {
        return arr.lower_name === value
      })
      cityPostalCode(obj[0].id).then(data => {
        this.optionPostalCode = data.sort((a, b) => {
          return a.zip - b.zip
        })
      })
    },
    /**
     * after_num1 - 仅退款
     * after_num2 - 退款退货
     * after_num3 - 补货
     * after_num4 - 召回
     * after_num5 - 修改地址
     * */
    openDialog() {
      this.loadingTable = true
      // 订单代发货
      if (this.status === '1') {
        this.optionType[1].disabled = true
        this.optionType[2].disabled = true
        this.optionType[3].disabled = true
      } else {
        this.optionType = this.optionType.map((arr) => {
          arr.disabled = false
          return arr
        })
        // this.optionType[4].disabled = true
      }

      if (!this.isRefund) {
        this.optionType[0].disabled = true
        // this.optionType[1].disabled = true
      }
      // this.goodsList()
      this.orderInfo()
      Object.keys(this.ruleForm).forEach(k => {
        this.ruleForm[k] = ''
      })
    },
    changeStorage(val) {
      this.warehouseList.map((arr) => {
        if (arr.value === val) {
          this.ruleForm.storage_address = arr.state + '/' + arr.city + '/' + arr.street
        }
      })
    },
    changeType(val) {
      this.ruleForm.storage_id = ''
      // this.selectionData = ''
      switch (val) {
        case '1':
          this.model.fieldsProduct = this.products
          break
        case '2':
          warehouseShop(this.shopId).then(data => {
            this.warehouseList = data
            this.model.fieldsProduct = this.productAfter
            if (this.model.fieldsProduct.length > 0) {
              this.$refs.multipleTable.clearSelection()
            }
          })
          break
        case '3':
          this.model.fieldsProduct = this.productAfter
          if (this.model.fieldsProduct.length > 0) {
            this.$refs.multipleTable.clearSelection()
          }
          break
        case '4':
          warehouseShop(this.shopId).then(data => {
            this.warehouseList = data
            console.log('this.productAfter', this.productAfter)
            this.model.fieldsProduct = this.productAfter
            if (this.model.fieldsProduct.length > 0) {
              this.$refs.multipleTable.clearSelection()
            }
          })
          break
        default:
          this.model.fieldsProduct = this.products
          break
      }
    },
    // 更新input不能输入的问题
    inputChange() { this.$forceUpdate() },
    // 订单地址详情
    orderInfo() {
      const vm = this
      vm.loading = true
      vm.$http.get(`/orderRecords/${vm.id}`).then((res) => {
        if (res.code === 10000) {
          // const arr = [1, 2, 4]
          // arr.forEach(e => {
          //   const value = res.data[`after_num${e}`]
          //   if (value > 0) {
          //     this.optionType[e - 1].disabled = true
          //   }
          // })
          if (res.data.after_refund_all) this.optionType[0].disabled = true

          const address = res.data.address[0]
          const address_stateorprovince = address.ship_stateorprovince ? address.ship_stateorprovince : address.address_stateorprovince
          vm.changeState(address_stateorprovince)

          const product = res.data.product[0]
          // 配件列表

          if (product.goods_id) {
            partListProduct(product.goods_id).then((data) => {
              vm.partList = data.map((arr) => {
                arr.disabled = false
                return arr
              })
            })
          }
          // if (product.buyer_user_firstname && product.buyer_user_lastname) {
          //   vm.formFieldsData.buyer_firstname = product.buyer_user_firstname
          //   vm.formFieldsData.buyer_lastname = product.buyer_user_lastname
          // } else {
          //   const name = address.address_name.split(' ')
          //   vm.formFieldsData.buyer_firstname = name[0]
          //   vm.formFieldsData.buyer_lastname = name[1]
          // }
          for (const key in address) {
            if (address[key]) {
              vm.formFieldsData[key] = address[key]
            }
          }
          vm.formFieldsDataOld = { ...vm.formFieldsData }
          vm.productAfter = res.data.product_after_order.map((arr) => {
            arr.quantity_purchased = arr.number
            arr.recall_num = 0
            arr.fill_amount = 0
            arr.transaction_price_currencyid = arr.transaction_price_currencyid ? arr.transaction_price_currencyid : 'USD'
            arr.transaction_price_value_all = accMul(arr.transaction_price_value, arr.number)
            return arr
          }).filter((item) => {
            return item.order_type_source === 1 // 排除补货订单
          })
          // console.log('=====vm.productAfter===', vm.productAfter)
          const dataArr = res.data.product.map((item) => {
            item.recall_num = 0
            item.fill_amount = 0
            item.transaction_price_value_all = accMul(item.transaction_price_value, item.quantity_purchased)
            return item
          })
          vm.model.fieldsProduct = dataArr
          vm.products = dataArr
          vm.loadingTable = false
        }
        vm.loading = false
      }).catch(() => {
        vm.loading = false
      })
    },
    // 商品详情
    goodsList() {
      const vm = this
      vm.$http.get(`/orders/productList/${vm.id}`).then((res) => {
        if (res.code === 10000) {
          const dataArr = res.data.map((item) => {
            item.recall_num = 0
            item.fill_amount = 0
            item.transaction_price_value_all = item.transaction_price_value * item.quantity_purchased
            return item
          })
          vm.model.fieldsProduct = dataArr
          vm.products = dataArr
          vm.loadingTable = false
        }
        vm.loadingTable = false
      })
    },
    // 关闭
    handleCancelDown() {
      this.$emit('update:formVisibleDown', false)
    },
    sum(arr) {
      return arr.reduce(function(prev, curr, idx, arr) {
        return prev + curr
      })
    },
    submitForm(formName) {
      let bol = true
      if (this.ruleForm.type === '3' || this.ruleForm.type === '5') {
        this.$refs.formFields.validate((valid) => {
          bol = valid
          console.log(valid)
        })
      }
      if (!bol) return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.ruleForm
          // 退款
          if (this.ruleForm.type === '1') {
            if (this.model.fieldsProduct[0].fill_amount > this.model.fieldsProduct[0].transaction_price_value_all) {
              return this.$message.error('退款金额不能大于总金额')
            }
            if (this.model.fieldsProduct[0].fill_amount <= 0) {
              return this.$message.error('请输入退款金额')
            }
            data.refund_amount = this.model.fieldsProduct[0].fill_amount
            data.fill_amount = this.model.fieldsProduct[0].fill_amount
          }
          // 召回
          if (this.ruleForm.type === '4') {
            if (!this.selectionData.length) return this.$message.error('至少选择一条数据')
            const recall_num = this.model.fieldsProduct.filter((item) => {
              return item.id === this.selectionData[0].id
              // return this.$computed.accAdd(count, item.quantity_purchased)
            }, 0)
            // console.log('=====recall_num=====', recall_num, recall_num[0].quantity_purchased)
            // return
            data.recall_num = recall_num[0].quantity_purchased
            // data.products = this.model.fieldsProduct.map((arr) => {
            //   return {
            //     id: arr.id,
            //     return_num: accAdd(arr.recall_num, arr.return_num),
            //     after_amount: accAdd(arr.after_amount, arr.fill_amount),
            //     order_deliver_id: arr.order_deliver_id
            //   }
            // })
            // data['order_deliver_id'] = data.products[0].order_deliver_id
            // data['recall_num'] = data.products[0].return_num
            // const listCount = data.products.map((arr) => {
            //   return Number(arr.after_amount)
            // })
            // data.refund_amount = this.sum(listCount)
            data.products = this.selectionData
            data.order_deliver_id = data.products[0].order_deliver_id
          }

          if (this.ruleForm.type === '2') {
            if (!this.selectionData.length) return this.$message.error('至少选择一条数据')
            if (!this.selectionData[0].recall_num) return this.$message.error('请输入退款数量')
            if (!this.selectionData[0].fill_amount) return this.$message.error('请输入退款金额')
            // const recall_num = this.model.fieldsProduct.reduce((count, item) => {
            //   return this.$computed.accAdd(count, item.recall_num)
            // }, 0)
            data.recall_num = this.selectionData[0].recall_num
            data.fill_amount = this.selectionData[0].fill_amount
            data.products = this.selectionData
            data.order_deliver_id = data.products[0].order_deliver_id
            // console.log('data.recall_num', data.recall_num)
          }

          if (this.ruleForm.type === '5' || this.ruleForm.type === '3') {
            data.address = [this.formFieldsData].map((arr) => {
              return {
                address_cityname: arr.address_cityname,
                address_country: arr.address_country,
                address_country_name: arr.address_country_name,
                address_email: arr.address_email,
                address_name: arr.address_name,
                address_phone: arr.address_phone,
                address_postalcode: arr.address_postalcode,
                address_stateorprovince: arr.address_stateorprovince,
                address_street1: arr.address_street1,
                address_street2: arr.address_street2,
                address_street3: arr.address_street3
              }
            })
            if (this.ruleForm.type === '5') {
              if (!objContrast(this.formFieldsDataOld, this.formFieldsData)) {
                this.$message.info('地址未作修改')
                return
              }
            }
          }
          if (this.ruleForm.type === '3') {
            if (this.ruleForm.replenish_type === 1) {
              if (!this.selectionData.length) return this.$message.error('至少选择一条数据')
              data.product = this.selectionData
            } else {
              data.product = this.model.fields
            }
          }
          // 商品fieldsProduct  配件 fields
          if (data.replenish_type === 1) {
            data.recall_num = this.model.fieldsProduct[0].quantity_purchased
          } else if (data.product && data.replenish_type === 2) {
            const recallCount = data.product.map((arr) => {
              return Number(arr.quantity_purchased)
            })
            data.recall_num = this.sum(recallCount)
          }
          // console.log('=======', data.recall_num, data.replenish_type)
          this.isbtn = true
          this.$http.put(`/orders/createdAfterSale/${this.id}`, data).then((res) => {
            if (res.code === 10000) {
              this.isbtn = false
              this.$message.success('售后申请添加成功')
              this.handleCancelDown()
              this.$emit('handleSearch')
            }
            this.isbtn = false
          }).catch(() => {
            this.isbtn = false
          })
        } else {
          console.log('>>>>>>-==========', valid)
          return false
        }
      })
    },
    selectionChange(data) {
      if (data.length > 1) {
        this.$refs.multipleTable.clearSelection()
        return this.$message.error('至多选择一条数据')
      }
      if (this.ruleForm.type === '4') {
        if (data.length) {
          this.ruleForm.refund_logistics = data[0].shipping_name
          this.ruleForm.logistics_no = data[0].shipping_code
        } else {
          this.ruleForm.refund_logistics = ''
          this.ruleForm.logistics_no = ''
        }
      }
      this.selectionData = data.map(v => v)
    },
    checkSelectable(row, index) {
      if (this.ruleForm.type === '2') {
        return row.delivery_state === 5 && row.return_num === 0 && row.order_type_source !== 2
      } else if (this.ruleForm.type === '4') {
        return row.delivery_state !== 1 && row.delivery_state !== 5 && row.number !== row.return_num && row.order_type_source !== 2
      } else if (this.ruleForm.type === '1') {
        return row.type !== 1
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
